#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define MAX_MSG_SIZE 1024

/*
 * ./server 8963
 */

int main(int argc,char** argv)
{
    int skfd,addrlen,ret;
    struct sockaddr_in addr,cltaddr;
    char buf[MAX_MSG_SIZE]={0};
    char sndbuf[MAX_MSG_SIZE]={0};

    //创建数据报式套接字skfd
    if(0>(skfd=socket(AF_INET,SOCK_DGRAM,0))){
         printf("Create Error");
         exit(1);
    }

    bzero(&addr,sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr=htonl(INADDR_ANY);
    addr.sin_port=htons(atoi(argv[1]));

    //将socket文件描述符skfd和本地端口和地址绑定起来
    if(0>(bind(skfd,(struct sockaddr*)&addr,sizeof(struct sockaddr_in)))){
         printf("Bind Error");
         exit(1);
    }

    //开始收发数据
    while(1) {
         ret=recvfrom(skfd,buf,MAX_MSG_SIZE,0,(struct sockaddr*)&cltaddr,&addrlen);
         if(ret < 0){
            printf("recv data from %s:%d error!",inet_ntoa(cltaddr.sin_addr),ntohs(cltaddr.sin_port));
         }else if(ret == 0){
            perror("client has been closing socket!");
         }else{
            printf("From %s:%d,%s",inet_ntoa(cltaddr.sin_addr),ntohs(cltaddr.sin_port),buf);
            memset(sndbuf,0,MAX_MSG_SIZE);
            switch(buf[0]){
                  case 'a':
                       strcpy(sndbuf,"After u ,lady...");
                  break;
                  case 'b':
                       strcpy(sndbuf,"Before u ,sir...");
                  break;
                  case 'c':
                       strcpy(sndbuf,"Can u?");
                       break;
                  default:
                       strcpy(sndbuf,"I dont't know what u want!");
            }
            sendto(skfd,sndbuf,strlen(sndbuf),0,(struct sockaddr*)&cltaddr,addrlen);
         }
         memset(buf,0,MAX_MSG_SIZE);
    }
    return 0;
}